<template>
  <div>
    <div class="fargot">
      找回密码
    </div>
    <div style="margin: 10rem 20rem;">
      <div class="number">手机验证</div>
      <div class="numtip">为了你的账户安全，请验证您的绑定手机号:</div>
      <van-field v-model="phone" label="手机号" placeholder="请输入手机号"
        style="margin-top: 40rem;height: 70rem;line-height: 60rem;" />
      <van-cell-group inset style="margin: 0;">
        <van-field v-model="sms" center clearable label="短信验证码" placeholder="请输入短信验证码"
          style="height: 70rem;line-height: 60rem;" @click-input="automatic">
          <template #button>
            <van-button size="small" type="primary"
              style="background-color: #ff5777;border: #ff5777;border-radius: 10rem;"
              @click="Verification">发送验证码</van-button>
          </template>
        </van-field>
      </van-cell-group>
      <button class="next" @click="next">下一步</button>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Toast } from 'vant';
import router from '@/router';
import { useUserStore } from '@/stores/user';
// import { useRouter } from 'vue-router';

const phone = ref('');
const sms = ref('');
const code = ref('');
const users = ref(JSON.parse(localStorage.getItem("users")) || []);
const userStore = useUserStore();
// 发送验证码的方法
const Verification = () => {
  if (phone.value.trim() === '') {
    Toast('请先输入手机号');
    return;
  }
  // 生成一个随机的6位数验证码
  code.value = Math.floor(100000 + Math.random() * 900000).toString();
  console.log('验证码:', code); // 输出验证码到控制台
  // code.value = code; // 将验证码设置为 sms 的值，以便用户填写

  Toast('验证码已发送');

};

// 自动填充验证码的方法
const automatic = () => {
  if (code.value) {
    sms.value = code.value;
  }
};

// 验证手机号是否存在于 users 中
const next = () => {
  const user = users.value.find((user) => user.phone === phone.value);
  if (user) {
    Toast('验证成功');
    userStore.setPhone(phone.value); // 存储手机号到 Pinia store
    router.push('/modify');
  } else {
    Toast('手机号未注册');
  }
};
</script>

<style scoped>
.fargot {
  width: 100%;
  height: 44rem;
  text-align: center;
  margin: 0 0 15rem 0;
  font-size: 20rem;
  line-height: 44rem;
  border-bottom: 1rem solid #d1cdcd;
  color: #999;
}

.number {
  font-size: 20rem;
  font-weight: bold;
  margin-left: 15rem;
}

.numtip {
  margin: 15rem 15rem;
  font-size: 14rem;
  color: #999;
}

.next {
  width: 100%;
  border-radius: 999rem;
  background-color: #ff5777;
  border: 1px solid #ff5777;
  color: white;
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  height: 44px;
  margin: 0;
  margin-top: 30rem;
  padding: 0;
  text-align: center;
  cursor: pointer;
  transition: opacity 0.2s;
  -webkit-appearance: none;
  font: inherit;
}
</style>
